package com.naiterui.ehp.ps.sms.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;

import org.slf4j.Logger;

import lombok.extern.slf4j.Slf4j;

/**
 * 过滤html特殊字符工具类
 *
 * @author
 * @since 1.0.0
 */
@Slf4j
public class FilterHtml<T> {
    private static String FILTERTYPE = "class java.lang.String";  // 只针对String类型的输入框做过滤
    private static String GET = "get";

    public void filter(T object, List<String> noFilterList) {

        Class<T> clazz = (Class<T>) object.getClass();
        Field[] fields = clazz.getDeclaredFields();
        Field field = null;
        String fieldName = null;
        String fieldMethodName = null;

        for (int i = 0; i < fields.length; i++) {
            try {
                field = fields[i];
                fieldName = field.getName();
                fieldMethodName = FilterHtml.GET + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
                Method getMethod = clazz.getMethod(fieldMethodName, new Class[]{});
                Object valueObject = getMethod.invoke(object, new Object[]{});

                if (valueObject != null && FilterHtml.FILTERTYPE.equals(getMethod.getReturnType().toString())) {
                    if (noFilterList == null || !noFilterList.contains(fieldName)) {
                        field.setAccessible(true);
                        field.set(object, xssProtect(valueObject.toString()));
                    }
                }

            } catch (NoSuchMethodException e1) {
                log.error("error in FilterHtml.filter,NoSuchMethodException", e1);
            } catch (Exception e) {
                log.error("error in FilterHtml.filter", e);
            }
        }
    }

    public static String xssProtect(String s) {
        if (s == null) {
            return "";
        }
        return s.replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;").replaceAll("'", "&apos;");
    }

    public static String htmlFilter(String s) {
        if (s == null) {
            return "";
        }
        return s.replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;").replaceAll("'", "&apos;").replaceAll("\r\n", "<br/>")
                .replaceAll("\n", "<br/>").replaceAll("\t", "    ").replaceAll("&nbsp;", " ").replaceAll("\u00A0", " ");
    }

    public static String specialHtmlFilter(String s) {
        if (s == null || s.equals("")) {
            return "";
        }
        return s.replaceAll("\r\n", "<br/>").replaceAll("\n", "<br/>").replaceAll("\t", "    ");
    }
}
